import router from "@/router/index";
import useUserStore from "@/store/modules/user";
import pinia from "@/store";
let userStore = useUserStore(pinia)

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
    let token = userStore.token
    let username = userStore.username
    if (token) {
        // 登录成功、不能访问登录页面
        if (to.path === '/login') {
            next('/')
        // 登录成功、其他页面都能访问
        } else {
            if (username) {
                next()
            } else {
                try {
                    await userStore.getUserInfo()
                    next()
                }catch(error){
                    await userStore.logout()
                    next('/login')
                }
            }
        }
    } else {
        // 未登录、能访问登录页面
        if (to.path === '/login') {
            next()
        // 未登录、访问其他页面跳转到登录页面
        } else {
            next('/login')
        }
    }
})
